package com.xiaoxin.xinlikesystem.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxin.xinlikesystem.common.BaseResponse;
import com.xiaoxin.xinlikesystem.common.DeleteRequest;
import com.xiaoxin.xinlikesystem.common.ResultUtils;
import com.xiaoxin.xinlikesystem.constant.UserConstant;
import com.xiaoxin.xinlikesystem.exception.BusinessException;
import com.xiaoxin.xinlikesystem.exception.ErrorCode;
import com.xiaoxin.xinlikesystem.exception.ThrowUtils;
import com.xiaoxin.xinlikesystem.model.dto.user.*;
import com.xiaoxin.xinlikesystem.model.entity.User;
import com.xiaoxin.xinlikesystem.model.vo.user.LoginUserVO;
import com.xiaoxin.xinlikesystem.model.vo.user.UserVO;
import com.xiaoxin.xinlikesystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @version 1.0
 * @Author 武小新
 * @Date 2025/5/10 15:24
 * @注释 用户层
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 1. 空值校验
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR, "请求内容为空");
        // 2. 注册
        String userAccount = userRegisterRequest.getAccount();
        String userPassword = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long result = userService.userRegister(userAccount, userPassword, checkPassword);

        // 3. 返回注册结果
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        // 1. 空值校验
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        // 2. 登录校验
        String userAccount = userLoginRequest.getAccount();
        String userPassword = userLoginRequest.getPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);

        // 3. 返回登录后脱敏对象
        return ResultUtils.success(loginUserVO);
    }


    /**
     * 用户注销
     */
    @PostMapping("/logout")
    @SaCheckLogin
    @Operation(summary = "用户注销", description = "登录用户注销登陆账号")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    /**
     * 获取当前登录用户（信息脱敏）
     */
    @GetMapping("/get/login")
    @Operation(summary = "获取登录用户信息", description = "登录用户查询个人信息")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }


    /**
     * 创建用户（仅管理员）
     */
    @PostMapping("/add")
    @SaCheckRole("admin")
    @Operation(summary = "创建用户（管）", description = "管理员创建用户账号")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        String encryptPassword = userService.getEncryptPassword(UserConstant.DEFAULT_PASSWORD);
        user.setPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }


    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @SaCheckRole("admin")
    @Operation(summary = "获取用户信息（管）", description = "管理员根据用户ID查询用户信息")
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }


    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    @Operation(summary = "获取用户信息", description = "根据用户ID查询用户信息（脱敏）")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }


    /**
     * 删除用户（仅管理员）
     */
    @PostMapping("/delete")
    @SaCheckRole("admin")
    @Operation(summary = "删除用户（管）", description = "管理员删除用户账号")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(result);
    }


    /**
     * 更新用户
     */
    @PostMapping("/update")
    @SaCheckRole("admin")
    @Operation(summary = "更新用户信息（管）", description = "管理员更新用户信息")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 分页获取用户封装列表（仅管理员）
     */
    @PostMapping("/list/page/vo")
    @SaCheckRole("admin")
    @Operation(summary = "获取用户列表（管）", description = "管理员查询所有用户")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }


}
